/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Client.InterfaceClientSocket;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author manelv8
 */
public class ServerSocketUDP implements InterfaceServerSocket {

    int porta;
    DatagramSocket srvUDP;
    DatagramPacket receivePacket;
    DatagramPacket sendPacket;

    public ServerSocketUDP(int porta) {
        try {
            this.porta = porta;
            srvUDP = new DatagramSocket(porta);
        } catch (SocketException ex) {
            Logger.getLogger(ServerSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    @Override
    public void enviarMsg(String msg, InterfaceClientSocket client) {
        try {
            byte[] sendData;


            InetAddress IPAddress = receivePacket.getAddress();
            int portReceive = receivePacket.getPort();


            sendData = msg.getBytes();
            System.out.println(msg);
            sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, portReceive);
            srvUDP.send(sendPacket);
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public String receberMsg(InterfaceClientSocket client) {


        byte[] receiveData;
        byte[] sendData;
        String msg = "";
        try {
            receiveData = new byte[1024];
            sendData = new byte[1024];
            //srvUDP = new DatagramSocket(porta);

            receivePacket = new DatagramPacket(receiveData, receiveData.length);
            srvUDP.receive(receivePacket);
            msg = new String(receivePacket.getData());
            System.out.println(msg);
        } catch (SocketException ex) {
            Logger.getLogger(ServerSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ServerSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }

        return msg;
    }

    @Override
    public void fechar() {
        this.srvUDP.close();
    }

    @Override
    public InterfaceClientSocket aceitar() {
 //       String msg = "";
  //      msg = receberMsg(null);
  //      msg = msg.trim();
 //      if (msg.equalsIgnoreCase("abrindo_conexao")) {

       //     enviarMsg("conexao_ok", null);
 //       }
        return null;
    }
}
